package org.zuel.huhuForum.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.zuel.huhuForum.component.SendMsg;
import org.zuel.huhuForum.constant.CommunityConstant;
import org.zuel.huhuForum.model.Comment;
import org.zuel.huhuForum.model.DiscussPost;
import org.zuel.huhuForum.param.Event;
import org.zuel.huhuForum.service.ICommentService;
import org.zuel.huhuForum.service.IDiscussPostService;
import org.zuel.huhuForum.util.HostHolder;
import org.zuel.huhuForum.util.RedisKeyUtil;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/comment")
@Api(tags = "评论")
public class CommentController implements CommunityConstant {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private IDiscussPostService discussPostService;

    @Autowired
    private SendMsg eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加评论
     * @param discussPostId 帖子id
     * @param text  评论文本
     * @param entityId  评论对象id
     * @param type    评论对象类型，1-帖子/2-评论
     * @return
     */
    @CrossOrigin
    @PostMapping("/add")
    @ApiOperation(value = "添加评论")
    public Map<String, String> addComment(@RequestParam(name="discussPostId", required = true) int discussPostId,
                             @RequestParam(name="text", required = true) String text,
                             @RequestParam(name="entityType", required = true) Integer type,
                             @RequestParam(name="entityId", required = true) Integer entityId) {
        Map<String,String> model =new HashMap<>();
        DiscussPost post=discussPostService.findDiscussPostById(discussPostId);
        if(post.getStatus().equals(TYPE_THERE)){
            model.put("msg", "codeMsg");
            model.put("code", "23");
            model.put("data","该帖已被终结，无法评论");
            return model;
        }else if(post.getStatus().equals(TYPE_TWE)){
            model.put("msg", "codeMsg");
            model.put("code", "23");
            model.put("data","该帖已被屏蔽,无法评论");
            return model;
        }
        Comment comment=new Comment();
        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        comment.setContent(text);
        comment.setEntityId(entityId);
        comment.setEntityType(type);
        comment.setTargetId(discussPostId);
        commentService.addComment(comment);

        // 触发评论事件（系统通知）
        Event event = new Event()
                .setTopic(TOPIC_COMMNET)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(comment.getEntityType())
                .setEntityId(comment.getEntityId())
                .setData("postId", discussPostId);
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            DiscussPost target = discussPostService.findDiscussPostById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        else if (comment.getEntityType() == ENTITY_TYPE_COMMENT) {
            Comment target = commentService.findCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        eventProducer.fireEvent(event);

        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            // 触发发帖事件，通过消息队列将其存入 Elasticsearch 服务器
            event = new Event()
                    .setTopic(TOPIC_CHANGE)
                    .setUserId(comment.getUserId())
                    .setEntityType(ENTITY_TYPE_POST)
                    .setEntityId(discussPostId);
            eventProducer.searchEvent(event);

            // 计算帖子分数
            String redisKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, discussPostId);
        }

        model.put("msg", "codeMsg");
        model.put("code", "200");
        model.put("data","评论添加成功");
        return  model;
    }
}
